package mysql

import (
	"backend/app/model"
	"database/sql"
	"errors"
	"fmt"
)

func QueryRoleByID(roleID int64) (*model.Role, error) {
	sqlStr := `select role_id, role_name from role where role_id=?`
	var mrole model.Role
	err := Db.Get(&mrole, sqlStr, roleID)
	if err == sql.ErrNoRows {
		return &mrole, errors.New("角色不存在")
	}
	if err != nil {
		fmt.Printf("scan failed, err : %v\n", err)
		return &mrole, err
	}
	return &mrole, err
}

func UpdateRole(role *model.Role) error {
	sqlStr := `update role set role_name=? where role_id=?`
	_, err := Db.Exec(sqlStr, role.RoleName, role.RoleId)
	return err
}

func InsertRole(role *model.Role) error {
	sqlStr := "insert into role(role_id, role_name) values(?,?)"
	_, err := Db.Exec(sqlStr, role.RoleId, role.RoleName)
	return err
}

func DeleteRole(roleID int64) error {
	sqlStr := `delete from role where rold_id=?`
	_, err := Db.Exec(sqlStr, roleID)
	return err
}

func CheckRoleIsExist(roleName string) (bool, error) {
	sqlStr := `select count(role_id) from role where role_name = ?`
	var count int
	err := Db.Get(&count, sqlStr, roleName)
	if err != nil {
		fmt.Printf("scan failed, err: %v\n", err)
		return false, err
	}
	if count > 0 {
		return true, nil
	}
	return false, nil
}

//------------------------------------------

func CheckUserRoleIsExist(roleId, userId int64) (bool, error) {
	sqlStr := `select count(role_id) from user_role where role_id=? and user_id=?`
	var count int
	err := Db.Get(&count, sqlStr, roleId, userId)
	if err != nil {
		fmt.Printf("scan failed, err: %v\n", err)
		return false, err
	}
	if count > 0 {
		return true, nil
	}
	return false, nil
}

func QueryUserRolesByID(roleID int64) ([]*model.UserRole, error) {
	sqlStr := `select role_id, user_id from user_role where role_id=?`
	mUserRole := []*model.UserRole{}
	err := Db.Get(&mUserRole, sqlStr, roleID)
	if err == sql.ErrNoRows {
		return mUserRole, errors.New("角色不存在")
	}
	if err != nil {
		fmt.Printf("scan failed, err : %v\n", err)
		return mUserRole, err
	}
	return mUserRole, err
}

func QueryUserRolesByUserId(userId int64) ([]*model.UserRole, error) {
	sqlStr := `select role_id, user_id from user_role where user_id=?`
	mUserRole := []*model.UserRole{}
	err := Db.Select(&mUserRole, sqlStr, userId)
	if err == sql.ErrNoRows {
		return mUserRole, errors.New("角色不存在")
	}
	if err != nil {
		fmt.Printf("scan failed, err : %v\n", err)
		return mUserRole, err
	}
	return mUserRole, err
}

func InsertUserRole(userRole *model.UserRole) error {
	sqlStr := "insert into user_role(role_id, user_id) values(?,?)"
	_, err := Db.Exec(sqlStr, userRole.RoleId, userRole.UserId)
	return err
}

func DeleteUserRole(userId, roleID int64) error {
	sqlStr := `delete from user_role where rold_id=? and user_id=?`
	_, err := Db.Exec(sqlStr, roleID, userId)
	return err
}
